﻿using ThresholdAssistant.DataContract.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace ThresholdAssistant.Tools.Extensions
{
    /// <summary>
    /// 枚举类型转换
    /// </summary>
    public static class EnumExtensions
    {
        /// <summary>
        /// 枚举转换
        /// </summary>
        /// <typeparam name="T">目标枚举</typeparam>
        /// <param name="enumNameOrValue">枚举名称或者枚举值</param>
        /// <returns></returns>
        public static T ToEnum<T>(this string enumNameOrValue) where T : Enum
        {
            //判断是否可以转换为整型
            if (!Enum.TryParse(typeof(T), enumNameOrValue, out object number))
            {
                Type type = typeof(T);
                string[] enumNames = type.GetEnumNames();
                string nameKey = enumNames.FirstOrDefault(name => name.Equals(enumNameOrValue, StringComparison.InvariantCultureIgnoreCase));
                if (!string.IsNullOrEmpty(nameKey))
                    enumNameOrValue = nameKey;
            }
            return (T)Enum.Parse(typeof(T), enumNameOrValue);
        }

        /// <summary>
        /// 自定义枚举扩展
        /// </summary>
        /// <param name="value">定义枚举</param>
        /// <param name="param">参数名称</param>
        /// <returns></returns>
        public static string GetDescription(this Enum value, string param = "")
        {
            FieldInfo field = value.GetType().GetField(value.ToString());
            var attribute = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
            if (attribute.Length > 0)
            {
                return (attribute[0] is DescriptionAttribute descriptionAttribute) ? $"{param}{descriptionAttribute.Description}" : "";
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 转换为枚举列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<EnumModel> ToEnumList<T>() where T : Enum
        {
            var list = new List<EnumModel>();
            var typeList = Enum.GetValues(typeof(T));
            foreach (var e in typeList)
            {
                EnumModel m = new EnumModel();
                object[] objArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (objArr != null && objArr.Length > 0)
                {
                    DescriptionAttribute da = objArr[0] as DescriptionAttribute;
                    m.Desction = da.Description;
                }
                m.Id = System.Convert.ToInt32(e);
                m.Name = e.ToString();
                list.Add(m);
            }
            return list;
        }
    }
}